package com.cci.kangdao.fieldService.service.impl;

import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.fieldService.dao.FieldServiceItemDao;
import com.cci.kangdao.fieldService.dao.FieldServiceWorkOrderDao;
import com.cci.kangdao.fieldService.manager.SyncCCGManager;
import com.cci.kangdao.fieldService.model.FieldServiceEngineer;
import com.cci.kangdao.fieldService.model.FieldServiceItem;
import com.cci.kangdao.fieldService.model.FieldServiceUpgrade;
import com.cci.kangdao.fieldService.model.FieldServiceWorkOrder;
import com.cci.kangdao.fieldService.model.SyncModel;
import com.cci.kangdao.fieldService.model.WorkOrderReport;
import com.cci.kangdao.fieldService.model.type.SyncInterface;
import com.cci.kangdao.fieldService.service.SyncCCGService;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.JsonUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author William Du
 * @date 2019/12/31
 */
@Service
public class SyncCCGServiceImpl implements SyncCCGService {

    private static final Logger logger = Logger.getLogger(SyncCCGService.class);

    @Resource
    private RedisClientUtils redisClientUtils;

    @Resource
    private SyncCCGManager syncCCGManager;

    @Resource
    private FieldServiceItemDao fieldServiceItemDao;

    @Resource
    private FieldServiceWorkOrderDao fieldServiceWorkOrderDao;

    @Override
    public void process(String itemId) {
        try {
            String syncListStr = redisClientUtils.hget(RedisKeys.fieldSyncMapKey(), itemId);
            if (StringUtils.isNotEmpty(syncListStr)) {
                List<SyncModel> syncModelList = JsonUtils.convertJsonArrayToList(syncListStr, SyncModel.class);
                if (CollectionUtils.isNotEmpty(syncModelList)) {
                    syncModelList = sortList(syncModelList);
                    List<SyncModel> successSyncList = new ArrayList<>();
                    for (SyncModel syncModel : syncModelList) {
                        Boolean syncFlag = Boolean.FALSE;
                        try {
                            if (syncModel.getSyncInterface().equals(SyncInterface.SYNC_ITEM)) {
                                FieldServiceEngineer engineer = BeanUtils.convert(syncModel.getArgs()[0], FieldServiceEngineer.class);
                                FieldServiceItem item = BeanUtils.convert(syncModel.getArgs()[1], FieldServiceItem.class);
                                syncFlag = this.syncServiceItemFromApp(engineer, item);
                            } else if (syncModel.getSyncInterface().equals(SyncInterface.SYNC_WORK)) {
                                FieldServiceWorkOrder workOrder = BeanUtils.convert(syncModel.getArgs()[0], FieldServiceWorkOrder.class);
                                syncFlag = this.syncServiceOrderFromApp(workOrder);
                            } else if (syncModel.getSyncInterface().equals(SyncInterface.SYNC_STATUS)) {
                                FieldServiceWorkOrder workOrder = BeanUtils.convert(syncModel.getArgs()[0], FieldServiceWorkOrder.class);
                                String message = null;
                                if(syncModel.getArgs().length > 1){
                                    if(null != syncModel.getArgs()[1]){
                                        message = (String) syncModel.getArgs()[1];
                                    }
                                }
                                syncFlag = this.syncOrderStatusFromApp(workOrder,message);
                            } else if (syncModel.getSyncInterface().equals(SyncInterface.SYNC_UPGRADE)) {
                                FieldServiceUpgrade upgrade = BeanUtils.convert(syncModel.getArgs()[0], FieldServiceUpgrade.class);
                                syncFlag = this.syncOrderStatusFromApp(upgrade);
                            } else if (syncModel.getSyncInterface().equals(SyncInterface.SYNC_REPORT)) {
                                WorkOrderReport report = BeanUtils.convert(syncModel.getArgs()[0], WorkOrderReport.class);
                                syncFlag = this.syncReportFromAPP(report);
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                        if (syncFlag) {
                            successSyncList.add(syncModel);
                        } else {
                            break;
                        }
                    }
                    syncModelList.removeAll(successSyncList);
                    if (CollectionUtils.isEmpty(syncModelList)) {
                        redisClientUtils.hdel(RedisKeys.fieldSyncMapKey(), itemId);
                    } else {
                        redisClientUtils.hset(RedisKeys.fieldSyncMapKey(), itemId, JsonUtils.toJsonString(syncModelList));
                    }
                }
            }
        } finally {
            redisClientUtils.delkey(RedisKeys.fieldSyncLockKey(String.valueOf(itemId)));
        }
    }

    private List<SyncModel> sortList(List<SyncModel> syncModelList) {
        return CollectionUtils.sort(syncModelList, new Comparator<SyncModel>() {
            @Override
            public int compare(SyncModel o1, SyncModel o2) {
                int order = o1.getOrder() - o2.getOrder();
                if (order == 0) {
                    order = (int) LocalTimeUtil.getDurationMinutes(o1.getActionTime(), o2.getActionTime());
                }
                return order;
            }
        });
    }


    @Override
    public Boolean syncServiceItemFromApp(FieldServiceEngineer engineer, FieldServiceItem fieldServiceItem) {
        logger.info("同步item");
        String crmNo = syncCCGManager.syncServiceItemFromApp(engineer, fieldServiceItem);
        if (StringUtils.isNotEmpty(crmNo)) {
            FieldServiceItem updateItem = new FieldServiceItem();
            updateItem.setId(fieldServiceItem.getId());
            updateItem.setCrmItemNo(crmNo);
            fieldServiceItemDao.updateByPrimaryKeySelective(updateItem);
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    @Override
    public Boolean syncServiceOrderFromApp(FieldServiceWorkOrder workOrder) {
        logger.info("同步wo");
        String crmNo = syncCCGManager.syncServiceOrderFromApp(workOrder);
        if (StringUtils.isNotEmpty(crmNo)) {
            FieldServiceWorkOrder updateOrder = new FieldServiceWorkOrder();
            updateOrder.setId(workOrder.getId());
            updateOrder.setCrmOrderNo(crmNo);
            fieldServiceWorkOrderDao.updateByPrimaryKeySelective(updateOrder);
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    @Override
    public Boolean syncOrderStatusFromApp(FieldServiceWorkOrder workOrder,String message) {
        return syncCCGManager.syncOrderStatusFromApp(workOrder,message);
    }

    @Override
    public Boolean syncOrderStatusFromApp(FieldServiceUpgrade upgrade) {
        return syncCCGManager.syncOrderStatusFromApp(upgrade);
    }

    @Override
    public Boolean syncReportFromAPP(WorkOrderReport report) {
        return syncCCGManager.syncReportFromAPP(report);
    }
}
